package com.party.web.web.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.LangUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.goods.Goods;
import com.party.core.model.goods.GoodsCoupons;
import com.party.core.model.order.*;
import com.party.core.model.wallet.Withdrawals;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.OrderActivityBizService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.goods.IGoodsService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderRefundTradeService;
import com.party.core.service.wallet.IWithdrawalService;
import com.party.core.service.wallet.biz.WithdrawalsBizService;
import com.party.pay.model.refund.WechatPayRefundResponse;
import com.party.web.biz.file.ExcelExportService;
import com.party.web.biz.order.OrderBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.order.OrderFormOutput;
import com.party.web.web.dto.output.wallet.WithdrawalOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 订单
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/order/order")
public class OrderFormController {

	@Autowired
	private IOrderFormService orderFormService;

	@Autowired
	private IGoodsCouponsService goodsCouponsService;
	@Autowired
	private IActivityService activityService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IProjectService projectService;
	@Autowired
	private OrderBizService orderBizService;

	@Autowired
	private IOrderRefundTradeService orderRefundTradeService;

	@Autowired
	private WithdrawalsBizService withdrawalsBizService;
	@Autowired
    private OrderActivityBizService orderActivityBizService;
	@Autowired
	private ExcelExportService excelExportService;
    @Autowired
    private IWithdrawalService withdrawalService;

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 订单详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "orderInfo")
	public ModelAndView orderInfo(String id) {
		ModelAndView mv = new ModelAndView("order/orderInfo");
		OrderForm orderForm = orderFormService.get(id);
		OrderFormOutput orderFormOutput = OrderFormOutput.transform(orderForm);
		// 核销码
		GoodsCoupons t = new GoodsCoupons();
		t.setOrderId(orderForm.getId());
		List<GoodsCoupons> goodsCoupons = goodsCouponsService.list(t);
		orderFormOutput.setGoodsCoupons(goodsCoupons);

		if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())) {
			Activity activity = activityService.get(orderForm.getGoodsId());
			if (activity != null) {
				orderFormOutput.setPicture(activity.getPic());
			}
		} else if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) {
			Project project = projectService.get(orderForm.getGoodsId());
			if (project != null) {
				orderFormOutput.setPicture(project.getPic());
			}
		} else if (orderForm.getType().equals(OrderType.ORDER_NOMAL.getCode()) || orderForm.getType().equals(OrderType.ORDER_CUSTOMIZED.getCode())) {
			Goods goods = goodsService.get(orderForm.getGoodsId());
			if (goods != null) {
				orderFormOutput.setPicture(goods.getPicsURL());
			}
		}
		// 获取商户名称
		String merchantName = orderActivityBizService.
				getMerchantName(orderForm.getMerchantId(), orderForm.getPaymentWay(), orderForm.getInitiatorId(), orderForm.getMerchantName());
		orderFormOutput.setMerchantName(merchantName);

		//交易流水
		OrderRefundTrade orderRefundTrade = orderRefundTradeService.recentlyByOrderId(id);
		WechatPayRefundResponse response = new WechatPayRefundResponse();
		if (null != orderRefundTrade && !Strings.isNullOrEmpty(orderRefundTrade.getData())) {
			response = JSONObject.toJavaObject(JSONObject.parseObject(orderRefundTrade.getData()), WechatPayRefundResponse.class);
		}

		mv.addObject("response", response);
		mv.addObject("orderForm", orderFormOutput);
		return mv;
	}

	/**
	 * 个人中心 交易明细
	 * @param page
	 * @return
	 */
	@RequestMapping("tradeList")
	public ModelAndView tradeList(Page page) {
		ModelAndView mv = new ModelAndView("system/member/tradeList");
		page.setLimit(15);
		OrderForm orderForm = new OrderForm();
		orderForm.setMemberId(RealmUtils.getCurrentUser().getId());
		orderForm.setType(OrderType.ORDER_LEVEL.getCode());
		Map<String, Object> params = Maps.newHashMap();
		params.put("isCrowdfund", "0");

		Map<String, Object> pageParams = CommonInput.appendPageParams(page);
		params.putAll(pageParams);

		Integer totalCount = orderFormService.newWebListCount(orderForm, params);
		page.setTotalCount(totalCount);

		List<OrderForm> orderForms = orderFormService.newWebListPage(orderForm, params);
		List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
			OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
			String label = OrderType.getValue(input.getType());
			orderFormOutput.setTypeName(label);
			return orderFormOutput;
		});
		mv.addObject("orderForms", orderFormOutputs);
		mv.addObject("page", page);
		memberIndexCommon(mv, null);
		return mv;
	}

	/**
	 * 个人中心 交易明细 导出
	 *
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("exportTradeOrder")
	public AjaxResult exportTradeOrder(HttpServletResponse response) {
		try {
			String fileName = "交易明细.xlsx";
			OrderForm orderForm = new OrderForm();
			orderForm.setMemberId(RealmUtils.getCurrentUser().getId());
			orderForm.setType(OrderType.ORDER_LEVEL.getCode());
			Map<String, Object> params = Maps.newHashMap();
			params.put("isCrowdfund", "0");
			List<OrderForm> orderForms = orderFormService.newWebListPage(orderForm, params);
			List<OrderFormOutput> orderFormOutputs = LangUtils.transform(orderForms, input -> {
				OrderFormOutput orderFormOutput = OrderFormOutput.transform(input);
				// 获取商户名称
				String merchantName = orderActivityBizService.
						getMerchantName(input.getMerchantId(), input.getPaymentWay(), input.getInitiatorId(), input.getMerchantName());
				orderFormOutput.setMerchantName(merchantName);
				orderFormOutput.setPaymentWayName(PaymentWay.getValue(input.getPaymentWay()));
				orderFormOutput.setTypeName(OrderType.getValue(input.getType()));
				orderFormOutput.setStatusName(OrderStatus.getValue(input.getStatus()));
				return orderFormOutput;
			});
			ExportExcel exportExcel = new ExportExcel("", OrderFormOutput.class).setDataList(orderFormOutputs);
			String allPath = excelExportService.getExcelPath(fileName, "wallet", exportExcel);
			return AjaxResult.success((Object) allPath);
		} catch (Exception e) {
			logger.error("导出交易明细异常{}", e);
		}
		return AjaxResult.error("导出异常");
	}

	/**
	 * 个人中心 收益明细
	 *
	 * @return
	 */
	@RequestMapping("orderList")
	public ModelAndView orderList(Page page, OrderForm orderForm, CommonInput input) {
		ModelAndView mv = new ModelAndView("system/member/orderList");
		page.setLimit(15);
		input.setIsDate(1);
		Map<String, Object> params = CommonInput.appendParams(input);
		List<OrderFormOutput> orderFormOutputs = orderBizService.memberOrderList(page, orderForm, params, input.getMemberName());
		mv.addObject("orderForms", orderFormOutputs);
		mv.addObject("page", page);

		// 订单总额
		Double orderTotal = orderBizService.getOrderTotal(false, orderForm.getType(),null);
		if (orderTotal != null) {
			mv.addObject("orderTotal", orderTotal);
		} else {
			mv.addObject("orderTotal", 0);
		}

		Map<Integer, String> orderTypes = Maps.newHashMap();
		orderTypes.put(OrderType.ORDER_ACTIVITY.getCode(), OrderType.ORDER_ACTIVITY.getValue());
		orderTypes.put(OrderType.ORDER_CROWD_FUND.getCode(), OrderType.ORDER_CROWD_FUND.getValue());
		mv.addObject("orderTypes", orderTypes);
		mv.addObject("input", input);

		memberIndexCommon(mv, orderForm.getType());
		return mv;
	}

    /**
     * 个人中心 提现明细
     *
     * @param page
     * @return
     */
    @RequestMapping("withdrawList")
    public ModelAndView withdrawList(Page page) {
		ModelAndView mv = new ModelAndView("system/member/withdrawList");
		page.setLimit(10);

		String currentId = RealmUtils.getCurrentUser().getId();
		Withdrawals withdrawal = new Withdrawals();
		withdrawal.setCreateBy(currentId);
		withdrawal.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		withdrawal.setType(Withdrawals.TYPE_BALANCE); // 余额
		List<Withdrawals> withdrawals = withdrawalService.listPage(withdrawal, page);
		List<WithdrawalOutput> withdrawalOutputs = LangUtils.transform(withdrawals, input -> {
			WithdrawalOutput output = WithdrawalOutput.transform(input);
			String account = input.getAccountNumber();
			account = withdrawalsBizService.formatAccountNumber(account);
			output.setAccountNumber(account);

			// 手续费
			double serviceFee = BigDecimalUtils.mul(input.getPayment(), Withdrawals.SERVER_FEE);
			serviceFee = BigDecimalUtils.round(serviceFee, 2);
			// 净额
			double netAmount = BigDecimalUtils.sub(input.getPayment(), serviceFee);

			output.setServiceFee(serviceFee);
			output.setNetAmount(netAmount);
			return output;
		});
		mv.addObject("withdrawals", withdrawalOutputs);
		mv.addObject("page", page);

		// 提现总额
		Double withdrawalTotal = withdrawalsBizService.getWithdrawalTotal(currentId, Withdrawals.TYPE_BALANCE,null);
		mv.addObject("withdrawalTotal", withdrawalTotal);

		memberIndexCommon(mv, null);
		return mv;
	}

    public void memberIndexCommon(ModelAndView mv, Integer type) {
        Map<String, Object> indexMap = orderBizService.memberIndexMap(false);
        mv.addAllObjects(indexMap);
    }

}
